package com.itheima.health.service.impl;


import com.aliyun.credentials.utils.StringUtils;
import com.itheima.health.common.R;
import com.itheima.health.mapper.MemberMapper;
import com.itheima.health.model.pojos.Member1;
import com.itheima.health.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpSession;



@Service
public class MemberServiceImpl implements MemberService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private MemberMapper memberMapper;

    public R login(String telephone, String validateCode, HttpSession session) {
            // 参数校验
            if (StringUtils.isEmpty(telephone) || StringUtils.isEmpty(validateCode)) {
                return R.error("手机号和验证码不能为空");
            }

            // 验证验证码
        if(session.getAttribute("validateCode")==null){
            return R.error("登录失败，验证码过期");
        }
        if (!validateCode.equals(session.getAttribute("validateCode").toString())) {
                return R.error("登录失败，验证码错误");
            }

            // 判断手机号是否存在
            Member1 member = getByTelephone(telephone);
            if (member == null) {
                // 新增用户
                member = new Member1();
                member.setTelephone(telephone);

                add(member);
            }

            // 登录成功，将用户信息保存到Redis
        /*    String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token, telephone, Duration.ofMinutes(30));*/

            return R.success("登录成功");
        }

        private Member1 getByTelephone(String telephone) {
            return memberMapper.getByTelephone(telephone);
        }

        private void add(Member1 member) {
            memberMapper.add(member);
        }
    }
